import React from 'react';
import styled from 'styled-components';
import { useTags } from 'hooks/useTags';
import { Toast } from 'antd-mobile';

const Wrapper = styled.section`
  background: #ffffff;
  padding: 12px 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-start;
  > ol {
    margin: 0 -8px;
    > li {
      background: #d9d9d9;
      border-radius: 18px;
      display: inline-block;
      padding: 2px 16px;
      font-size: 14px;
      margin: 8px;
      &.selected {
        background: #666;
        color: #eee;
      }
    }
  }
  button {
    background: #fff;
    border: none;
    border-bottom: 1px solid #333;
    padding: 2px 4px;
    color: #666;
    margin-top: 8px;
  }
`;

type Props = {
  value: number[];
  onChange: (selected: number[]) => void;
};

export const TagsSection: React.FC<Props> = props => {
  const { tags, addTag } = useTags();
  const selectedTagIds = props.value;

  const onToggleTag = (tagId: number) => {
    const index = selectedTagIds.indexOf(tagId);
    if (index >= 0) {
      // 如果 tagId 已被选中，就复制所有被选中的 tagId，作为新的 selectedTagIds
      props.onChange(selectedTagIds.filter(t => t !== tagId));
    } else {
      const finalTags = [...selectedTagIds, tagId];
      if (finalTags.length > 2) {
        Toast.info('最多选择两个标签', 2);
        return;
      }
      props.onChange(finalTags);
    }
  };
  const getClass = (tagId: number) =>
    selectedTagIds.indexOf(tagId) >= 0 ? 'selected' : '';
  return (
    <Wrapper>
      <ol>
        {tags.map(tag => (
          <li
            key={tag.id}
            onClick={() => {
              onToggleTag(tag.id);
            }}
            className={getClass(tag.id)}
          >
            {tag.name}
          </li>
        ))}
      </ol>
      <button onClick={addTag}>新增标签</button>
    </Wrapper>
  );
};
